package tezhongbing.annotation;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Map;

public class ConversionService {
	@SuppressWarnings("unchecked")
	public static <T> T convertMapToBean(Map<String, String> map, Class<T> clazz) throws InstantiationException, IllegalAccessException{
		Field[] fields = clazz.getDeclaredFields();
		Object obj = clazz.newInstance();
		for(Field field : fields){
			if(Modifier.isStatic(field.getModifiers()) || Modifier.isFinal(field.getModifiers()))
				continue;
			if(!field.isAccessible()) field.setAccessible(true);
			Column column = field.getAnnotation(Column.class);
			if(column==null)
				continue;
			String value = map.get(column.name());
			Class<?> fieldType = field.getType();
			if(fieldType == String.class){
				field.set(obj, value);
			}else if(fieldType == Integer.class){
				field.set(obj, Integer.parseInt(value));
			}else if (fieldType == int.class){
				field.set(obj, Integer.parseInt(value));
			}else{
				//TODO 更多类型自己补充
			}
		}
		return (T)obj;
	}
	
}
